package org.example.javasrcimplementbyself.HashMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

public class SimpleHashMap<K, V> {
    // 定义默认的数组大小
    private static final int DEFAULT_CAPACITY = 16;
    private LinkedList<Entry<K, V>>[] buckets;

    // Entry类，用于存储键值对
    private static class Entry<K, V> {
        K key;
        V value;

        Entry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    // 构造函数
    public SimpleHashMap() {
        buckets = new LinkedList[DEFAULT_CAPACITY];
        for (int i = 0; i < DEFAULT_CAPACITY; i++) {
            buckets[i] = new LinkedList<>();
        }
    }

    // 哈希函数，计算键的哈希值
    private int hash(K key) {
        return Math.abs(key.hashCode()) % buckets.length;
    }

    // put方法：插入或更新键值对
    public void put(K key, V value) {
        int index = hash(key);
        LinkedList<Entry<K, V>> bucket = buckets[index];

        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                entry.value = value; // 更新值
                return;
            }
        }
        bucket.add(new Entry<>(key, value)); // 新增键值对
    }

    // get方法：根据键获取值
    public V get(K key) {
        int index = hash(key);
        LinkedList<Entry<K, V>> bucket = buckets[index];

        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                return entry.value;
            }
        }
        return null; // 未找到键
    }

    // remove方法：根据键删除键值对
    public void remove(K key) {
        int index = hash(key);
        LinkedList<Entry<K, V>> bucket = buckets[index];

        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                bucket.remove(entry);
                return;
            }
        }
    }

    // 打印HashMap内容（用于调试）
    public void printMap() {
        for (int i = 0; i < buckets.length; i++) {
            LinkedList<Entry<K, V>> bucket = buckets[i];
            System.out.print("Bucket " + i + ": ");
            for (Entry<K, V> entry : bucket) {
                System.out.print(entry.key + "=" + entry.value + " ");
            }
            System.out.println();
        }
    }


    // 测试代码
    public static void main(String[] args) {
        SimpleHashMap<Student, Integer> map = new SimpleHashMap<Student, Integer>();
        Student student = new Student("男", "yu", 18);
        Student student2 = new Student("男", "yyh", 17);
        Student student1 = new Student("男", "yu", 18);
        map.put(student, 1);
        map.put(student1, 2);
        map.put(student2, 3);
        System.out.println(map.get(student));
        System.out.println(map.get(student1));
    }
}

class Student{
    public Student(String sex, String name, int age){
        this.sex = sex;
        this.name = name;
        this.age = age;
    }


    String sex;
    String name;
    int age;
}